package net.k3rnel.abugadro;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import net.k3rnel.abugadro.Project.Projects;
import net.k3rnel.abugadro.gcodes.beans.GoogleCode.GCode;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler;
import net.k3rnel.abugadro.util.SyncService;
import net.k3rnel.abugadro.util.UIUtils;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class ProjectEditor extends Activity implements AsyncQueryListener{

	public static final String TAG = "Abugadro ProjectEditor";
	private EditText mProjectName;
	private Spinner  mProjectType;
//	private EditText mUsername;
//	private EditText mPassword;
//	private CheckBox mRememberPassword;
//	ProgressDialog progressDialog;
	private NotifyingAsyncQueryHandler mHandler;
	private boolean mEditMode = false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_projects_add);

		final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE);
		((TextView) findViewById(R.id.title_text)).setText(
				customTitle != null ? customTitle : getTitle());

		Spinner typeSpinner = (Spinner) findViewById(R.id.project_types_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.project_types, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		typeSpinner.setAdapter(adapter);

//		progressDialog = new ProgressDialog(this);
//		progressDialog.dismiss();

		mProjectName = (EditText) findViewById(R.id.project_name_entry);
		mProjectType = (Spinner) findViewById(R.id.project_types_spinner);
//		mUsername = (EditText) findViewById(R.id.project_username_entry);
//		mPassword = (EditText) findViewById(R.id.project_password_entry);
//		mRememberPassword = (CheckBox) findViewById(R.id.project_check_pass);

		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		final String action = getIntent().getAction();
		if (Intent.ACTION_EDIT.equals(action) && savedInstanceState == null) {
			mEditMode = true;
			//			// Start background query to load current state
			final Uri projectUri = getIntent().getData();
			mHandler.startQuery(projectUri, ProjectsQuery.PROJECTION);
			((Button) findViewById(R.id.proj_del)).setText(R.string.option_delete);
			((Button) findViewById(R.id.proj_add)).setText(R.string.option_save);
			((TextView) findViewById(R.id.title_text)).setText(R.string.title_project_edit);
		}

		Button button = (Button) findViewById(R.id.proj_add);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String projName = mProjectName.getText().toString().toLowerCase();
				String projectType = mProjectType.getSelectedItem().toString();
				int type = 0;
				if(projectType.equals("Launchpad"))
					type = 1;
				//Else, its a GoogleCode project. No need to else. 
//				String username = mUsername.getText().toString();
//				String password = mPassword.getText().toString();
//				boolean rememberPass = mRememberPassword.isChecked();
				if(!projName.equals("")){
					checkProject(projName,type);
					
				} else createDialog("Wait a minute...","That Project doesn't exist!\nCheck for Typos and double-check the Bug Tracker Type");
			}
		});
	}

	/** {@inheritDoc} */
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		try {
			if (!cursor.moveToFirst()) return;

			// Load current project content for editing
			mProjectName.setText(cursor.getString(ProjectsQuery.NAME));
			mProjectName.setClickable(false);
			mProjectName.setEnabled(false);
			mProjectName.setFocusable(false);


			mProjectType.setSelection(cursor.getInt(ProjectsQuery.TYPE));
			mProjectType.setFocusable(false);
			mProjectType.setClickable(false);
			mProjectType.setEnabled(false);

//			mUsername.setText(cursor.getString(ProjectsQuery.USERNAME));
//			String password = cursor.getString(ProjectsQuery.PASSWORD);
//			if(password!=null&&!password.equals(""))
//				mRememberPassword.setChecked(true);
//			mPassword.setText(password);

		} finally {
			if(cursor!=null)
				cursor.close();
		}
	}

	/** Handle "home" title-bar action. */
	public void onHomeClick(View v) {
		UIUtils.goHome(this);
	}
	/** Handle "home" title-bar action. */
	public void onCancelClick(View v) {
		if(!mEditMode)
			UIUtils.goHome(this);
		else{
			showDialog(R.id.dialog_discard_confirm);
		}
	}
	private void deleteProject() {
		if (mEditMode) {
			final Uri projectUri = getIntent().getData();
			final Uri gcodeUri = GCode.buildUri(ProjectsDB.getInstance().getGoogleIdbyProjectId(getContentResolver(), Integer.parseInt(projectUri.getPathSegments().get(1)))+"");
			final Uri issuesUri = Uri.parse("content://"+ AbugadroContentProvider.AUTHORITY + "/gcode/"+gcodeUri.getPathSegments().get(1)+"/issues/");
			final Uri labelsUri = Uri.parse("content://"+ AbugadroContentProvider.AUTHORITY + "/gcode/"+gcodeUri.getPathSegments().get(1)+"/issues/*/labels");
			final Uri commentsUri = Uri.parse("content://"+ AbugadroContentProvider.AUTHORITY + "/gcode/"+gcodeUri.getPathSegments().get(1)+"/issues/*/comments");
			final Uri commentUpdatesUri = Uri.parse("content://"+ AbugadroContentProvider.AUTHORITY + "/gcode/"+gcodeUri.getPathSegments().get(1)+"/issues/*/comments/*/commentupdates");
			mHandler.startDelete(commentUpdatesUri);
			mHandler.startDelete(commentsUri);
			mHandler.startDelete(labelsUri);
			mHandler.startDelete(issuesUri);
			mHandler.startDelete(gcodeUri);
			mHandler.startDelete(projectUri);
		} 

		finish();
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case R.id.dialog_discard_confirm: {
			return new AlertDialog.Builder(this)
			.setTitle(R.string.title_project_delete)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setMessage(R.string.project_delete_confirm)
			.setNegativeButton(android.R.string.cancel, null)
			.setPositiveButton(android.R.string.ok, new DiscardConfirmClickListener())
			.setCancelable(false)
			.create();
		}
//		case R.id.dialog_progress:{
//			progressDialog = new ProgressDialog(ProjectEditor.this);
//			progressDialog.setIndeterminate(true);
//			progressDialog.setMessage("Loading...");
//			progressDialog.setCancelable(false);
//			return progressDialog;
//		}
		}
		return null;
	}

	private class DiscardConfirmClickListener implements DialogInterface.OnClickListener {
		public void onClick(DialogInterface dialog, int which) {
			deleteProject();
		}
	}
	private void createDialog(String title, String text) {
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("Ok", null)
		.setTitle(title)
		.setMessage(text)
		.create();
		ad.show();
	}

	private void checkProject(final String projectName, final int type) {
		Thread t = new Thread() {
			public void run() {
				Looper.prepare();
				try {
					switch(type){
					case 0:
						try{
							if(ProjectsDB.getInstance().isProjectInDB(getContentResolver(),projectName,type)==0){
//								showDialog(R.id.dialog_progress);
								String auth = "";
//								if(!username.equals("")&&!password.equals(""))
//								try{
//									List<NameValuePair> params = new ArrayList<NameValuePair>(2);
//									params.add(new BasicNameValuePair("accountType", "GOOGLE"));
//									params.add(new BasicNameValuePair("Email", username));
//									params.add(new BasicNameValuePair("Passwd", password));
//									params.add(new BasicNameValuePair("service", "code"));
//									params.add(new BasicNameValuePair("source", "Abugadro-v"+R.string.version));
//									HttpPost postRequest = new HttpPost("https://www.google.com/accounts/ClientLogin");
//									postRequest.setEntity(new UrlEncodedFormEntity(params));
//									HttpResponse response = new DefaultHttpClient().execute(postRequest);
//									if(response.getStatusLine().getStatusCode()==200){
//										HttpEntity entity = response.getEntity();
//										if(entity != null){
//											InputStream inputStream = entity.getContent();
//											auth = convertStreamToString(inputStream);
//											Log.i(TAG,auth);
//										}
//									}else if(response.getStatusLine().getStatusCode()==403){
//										//Display bad password prompt
//										progressDialog.dismiss();
//										HttpEntity entity = response.getEntity();
//										if(entity != null){
//											InputStream inputStream = entity.getContent();
//											auth = convertStreamToString(inputStream);
//											Log.i(TAG,auth);
//										}
//										
//										auth="forbidden";
//										createDialog("FYI","That Username/Password combination didn't work");
//									}else{
//										progressDialog.dismiss();
//										HttpEntity entity = response.getEntity();
//										if(entity != null){
//											InputStream inputStream = entity.getContent();
//											auth = convertStreamToString(inputStream);
//											Log.i(TAG,auth);
//										}
//										
//										auth="forbidden";
//										createDialog("FYI","That Username/Password combination didn't work. \nError: "+response.getStatusLine().getStatusCode());
//									}
//								} catch (ClientProtocolException e) {
//									//e.printStackTrace();
//									Log.e("Abugadro","ClientProtocolE",e);
//								} catch (IOException e) {
//									Log.e("Abugadro","IOException",e);
//								}
								if(!auth.equals("forbidden")){
									URL url = new URL("http://code.google.com/feeds/issues/p/"+projectName+"/issues/full/?max-results=1");
									HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
									urlc.setRequestProperty("User-Agent", "Abugadro for Android v"+R.string.version);
									urlc.setRequestProperty("Connection", "close");
									if(!auth.equals("")&&!auth.equals("forbidden")){
										urlc.setRequestProperty("Authorization", "GoogleLogin auth=\""+auth+"\"");
									}
									urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
									urlc.connect();
									if (urlc.getResponseCode() == 200) {
										Log.i(TAG,"Project Found");
//										progressDialog.dismiss();
										int gcodeId = ProjectsDB.getInstance().addNewProject(getContentResolver(), projectName, type);
										Log.i(TAG,"Project Created");
										Uri uri = GCode.buildUri(gcodeId+"");
										new SyncService().startThread(new Handler(), getContentResolver(), uri, 0);
										finish();
									}else{
//										progressDialog.dismiss();
										Log.i(TAG,"Error "+urlc.getResponseCode());
										createDialog("Wait a minute...","That Project doesn't exist, or we don't have access to it.\nError: "+urlc.getResponseCode());
									}
								}else{
//									progressDialog.dismiss();
								}
							}else{
//								ProjectsDB.getInstance().updateProjectFromTitle(getContentResolver(), projectName, type, username, password);
								finish();
							}
						} catch (MalformedURLException e1) {
//							progressDialog.dismiss();
							Log.e(TAG,"MalformedURL",e1);
							createDialog("Urgh.. MalformedURL!","You broke the URL! Project Names don't use slashes, that's probably it.");
						} catch (IOException e) {
//							progressDialog.dismiss();
							Log.e(TAG,"IOException",e);
							createDialog("Gah! IOException!","You know what an IOException is, right? \nNo Internet Connectivity. We sorta need that to add a project.");
						}
						break;
					case 1:
						try{
							if(ProjectsDB.getInstance().isProjectInDB(getContentResolver(),projectName,type)!=0){
//								showDialog(R.id.dialog_progress);
								URL url = new URL("http://feeds.launchpad.net/"+projectName+"/latest-bugs.atom"); //Need to find a way to only get one bug or two
								HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
								urlc.setRequestProperty("User-Agent", "Abugadro for Android v"+R.string.version);
								urlc.setRequestProperty("Connection", "close");
								urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
								urlc.connect();
								if (urlc.getResponseCode() == 200) {
									Log.i(TAG,"Project Found");
									ProjectsDB.getInstance().addNewProject(getContentResolver(), projectName, type);
									Log.i(TAG,"Project Created");
//									progressDialog.dismiss();
									finish();
								}else{
//									progressDialog.dismiss();
									Log.i(TAG,"Error "+urlc.getResponseCode());
									createDialog("Wait a minute...","That Project doesn't exist, or we don't have access to it.\nError: "+urlc.getResponseCode());
								}
							}else{
//								ProjectsDB.getInstance().updateProjectFromTitle(getContentResolver(), projectName, type, username, password);
								finish();	
							}
						} catch (MalformedURLException e1) {
//							progressDialog.dismiss();
							Log.e(TAG,"MalformedURL",e1);
							createDialog("Urgh.. MalformedURL!","You broke the URL! Project Names don't use slashes, that's probably it.");
						} catch (IOException e) {
//							progressDialog.dismiss();
							Log.e(TAG,"IOException",e);
							createDialog("Gah! IOException!","You know what an IOException is, right? \nNo Internet Connectivity. We sorta need that to add a project.");
						}
						break;
					default:
						finish();
						break;
					}

					//Create Account
				} catch (Exception e) {
					createDialog("What a Terrible Failure", e.getMessage()); //This should never happen. 
				}
				Looper.loop();                
			}
		};
		t.start();


	}
//	private static String convertStreamToString(InputStream is) {
//		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//		StringBuilder stringBuilder = new StringBuilder();
//		String line = null;
//		try {
//			while ((line = reader.readLine()) != null) {
//				if(line.contains("Auth="))
//					stringBuilder.append(line.substring(5));
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			try {
//				is.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		return stringBuilder.toString();
//	}
	/** {@link Projects} query parameters. */
	private interface ProjectsQuery {
		String[] PROJECTION = {
				BaseColumns._ID,
				Projects.NAME,
				Projects.TYPE,
		};
		int NAME = 1;
		int TYPE = 2;
	}
}